import { Injectable } from '@angular/core';

import { BlockUiService } from './blockui.service';
import { DialogXWService } from './dialog.service';
import {HttpClient, HttpHeaders, } from '@angular/common/http';


@Injectable()
export class HttpService {

  private domain = '';
  private token = '';

  constructor(private http: HttpClient, private block: BlockUiService, private ds: DialogXWService) {

  }
  /**
         * 通用参数 处理
         */
  getRequestOptionsArgs() {
    let header = new HttpHeaders();
    header.append('X-Requested-With', 'XMLHttpRequest');
    let option = { headers: header };
    return option;
  }

  /**
         * http get重写
         */
  get(url: string, option?) {
    if(!option) option = { params: { ts: new Date().getTime() } };
    Object.assign(option, this.getRequestOptionsArgs());
    this.block.blockUI();
    return this.http.get(url, option).toPromise().then((res:any) => {
      return this.HandSuccessResult(res);
    }).catch(res => {
      this.HandErrorResult(res);
    });
  }


  /**
         * http post重写
         */
  post(url: string, body?: any, option?) {
    if(!option) option={};
    Object.assign(option, this.getRequestOptionsArgs());
    this.block.blockUI();
    return this.http.post(url, body, option).toPromise().then((res:any) => {
      return this.HandSuccessResult(res);
    }).catch(res => {
      this.HandErrorResult(res);
    });
  }

  /**
       * 处理http正确返回结果
       */
  HandSuccessResult(res) {
    let httpresult = res;
    if(httpresult.result){
      this.block.UnBlockUI();
      return httpresult.data;
    }
    else{
     // this.mydialog.openMessage(httpresult.message, "操作失败", "error");
      throw res; 
    }
  }
  /**
       * 处理http错误正确返回结果
       */
  HandErrorResult(res) {
    if(res.status==401){
      location.href=location.origin;
      return;
    }
    this.block.UnBlockUI();
    if (res.ok) {
      let result = res;
      this.ds.Error(result.message||'抱歉,无任何错误信息返回!');
    }
    else {
      this.ds.Error(res.statusText||'网络异常!');
    }
    throw res;

  }

}
